package org.example.springcache.service.impl;

import org.example.springcache.domain.User;
import org.example.springcache.service.IUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements IUserService {

    @Override
    @Cacheable(value = "userCache",key = "#id",unless = "#result == null ")
    public User getUserById(int id) {
        //查询数据库逻辑 ......
        System.out.println("查询数据库， id = " + id);
        return new User(id,"用户"+ id);
    }

    @Override
    @CachePut(value = "userCache", key = "#user.id")//key与查询时一致（都是用户id）
    public User update(User user) {
        //更新数据库逻辑
        System.out.println("更新数据库，user = " + user);
        return user; //返回更新后的用户，存入缓存
    }

    @Override
    @CacheEvict(value = "userCache",key = "#id")
    public void delete(int id) {
        //删除数据库的逻辑
        System.out.println("清空所有用户缓存");
    }
}
